/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
#define BPF_NO_GLOBAL_DATA
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include "helloworld.h"

char LICENSE[] SEC("license") = "Dual BSD/GPL";

/* Create an array with 1 entry instead of a global variable
 * which does not work with older kernels */
struct {
	__uint(type, BPF_MAP_TYPE_ARRAY);
	__uint(max_entries, 1);
	__type(key, u32);
	__type(value, struct bpf_transfer);
} my_data_map SEC(".maps");


SEC("tracepoint/spi/spi_message_done")
int handle_tp(void *ctx)
{
	struct bpf_transfer value = {};
	struct bpf_transfer *p = NULL;
	u32 index = 0;
	unsigned long pid = bpf_get_current_pid_tgid() >> 32;
	unsigned long ns = bpf_ktime_get_ns();
	p = bpf_map_lookup_elem(&my_data_map, &index);

	if (!p)
		return 1;
	
	// if(p->count <= 0)
	// 	p->count = 0;

	value.count = p->count;
	value.pid = pid;
	value.ns = ns;
	if(value.count <= 0)
		value.count = 0;
	
	value.count ++;
	bpf_map_update_elem(&my_data_map, &index, &value, BPF_ANY);
	bpf_printk("BPF triggered from PID %d count: %d.\n", pid, value.count);
	
	return 0;
}
